'use strict';


const makeListNode =  (list)  => {
    let head = null;
    let cur = head;
    for(const val of list) {
        const next = { val, next: null };
        if (!head) {
            head = next;
            cur = head;
        } else {
            cur.next = next;
            cur = cur.next;
        }
    }
    return head;
}

const runner = (arr1, arr2) => {
    const l1 = makeListNode(arr1);
    const l2 = makeListNode(arr2);

    const result = addTwoNumbers(l1, l2);
    console.log(result);
}

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
 var addTwoNumbers = function(l1, l2) {
    let result = null;
    let cur = null;
    let carry = 0;
    while(l1 || l2) {
        let x = 0;
        if (l1) {
            x += l1.val;
            l1 = l1.next;
        }
        if (l2) {
            x += l2.val;
            l2 = l2.next;
        }
        x += carry;
        if (x > 9) {
            x -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
        const curNode = {
            val: x,
            next: null,
        };
        if (!result) {
            result = curNode;
            cur = result;
        } else {
            cur.next = curNode;
            cur = cur.next;
        }
    }
    if (carry) {
        cur.next = { val: 1, next: null };
    }
    return result;
};
